var list = $('#list .tab-con');
var container = $('.mod-tab');
var index = 1;
var timer;
var buttons = $('#gb-tab a');
var prev = $('#prev');
var next = $('#next');
var stateNext = true;
var statePrev = true;

$(document).ready(function(){
    container.mouseover(function(){
        stop();
    });
    container.mouseout(function(){
        play();
    });
    for (var i = 0; i < buttons.length; i++) {
        (function (i) {
            buttons[i].onclick = function () {
                index = i + 1;
                imgShow();
                buttonsShow();
            }
        })(i)
    }
    prev.click(function () {
        if(statePrev){
            index -= 1;
            if (index < 1) {
                index = 8
            }
            imgShow();
            buttonsShow();
            statePrev = false;
            setTimeout(function(){
                statePrev = true;
            },2000)
        }
    });

    next.click(function () {
        //由于上边定时器的作用，index会一直递增下去，我们只有5个小圆点，所以需要做出判断
        if(stateNext){
            index += 1;
            if (index > 8) {
                index = 1
            }
            imgShow();
            buttonsShow();
            stateNext = false;
            setTimeout(function(){
                stateNext = true
            },2000)
        }
    });
});

function play() {
    //重复执行的定时器
    timer = setInterval(function () {
        index += 1;
        if (index > 8) {
            index = 1
        }
        imgShow();
        buttonsShow();
    }, 4000)
}

function stop() {
    clearInterval(timer);
}

function imgShow(){
    for (var i = 0; i < list.length; i++) {
        if (list.eq(i).css('opacity') == 1) {
            list.eq(i).fadeTo(1000,0);
        }
    }
    list.eq(index - 1).fadeTo(1000,1);
}

function buttonsShow() {
    //将之前的小圆点的样式清除
    for (var i = 0; i < buttons.length; i++) {
        if (buttons[i].className == "item2") {
            buttons[i].className = "item";
        }
    }
    buttons[index - 1].className = "item2";
}


play();

